import styled from 'styled-components';
import React, { CSSProperties, useEffect, useRef, useState } from 'react';
import { Card, Button, Select, Input } from 'antd';
import { open, save } from '@tauri-apps/plugin-dialog';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

import { ToolsHeader, CategoryList } from '../../../../components';
import { DataSource, execute } from '@/services';
import { metaGenerateSQLByDomain } from '@/services/local';

export interface DataValuesDomainPersistencePanelProps {
    style?: CSSProperties;
    dataSource: DataSource;
    domainIdentifier: string;
}

const STORAGE_TYPES = [{
    identifier: 'mysql',
    name: 'MySQL',
}, {
    identifier: 'sqlite',
    name: 'SQLite',
}]
export const DataValuesDomainPersistencePanel: React.FC<DataValuesDomainPersistencePanelProps> = (props) => {

    const [loading, setLoading] = useState<boolean>(false);

    const [databaseType, setDatabaseType] = useState<'sqlite' | 'mysql'>('sqlite');

    const [content, setContent] = useState<string>('');

    const [editor, setEditor] = useState<monaco.editor.IStandaloneCodeEditor | null>(null);

    const monacoEl = useRef(null);

    useEffect(() => {
        if (monacoEl) {
            setEditor((editor) => {
                if (editor) return editor;

                let editorObj = monaco.editor.create(monacoEl.current!, {
                    automaticLayout: true,
                    value: '',
                    language: 'sql',
                    readOnly: true,
                });
                return editorObj;
            });
        }

        return () => editor?.dispose();
    }, [monacoEl.current]);

    useEffect(() => {
        editor?.setValue(content);
    }, [content, editor]);


    return (
        <Container style={props.style}>
            <Top>
                <Select
                    style={{ flex: 1 }}
                    value={databaseType}
                    onChange={async (value) => {
                        setDatabaseType(value);
                        setContent('');
                    }}
                    options={STORAGE_TYPES.map((item, index) => {
                        return {
                            value: item.identifier,
                            label: item.name
                        };
                    })} />
                <Button
                    style={{
                        width: '220px'
                    }}
                    loading={loading}
                    type={'primary'}
                    onClick={async () => {
                        setLoading(true);
                        try {
                            let sqls = await metaGenerateSQLByDomain(props.dataSource.id, props.domainIdentifier, databaseType);
                            console.log(sqls);
                            setContent(sqls.join(";\n"));
                        } catch (err) {
                            console.error(err);
                        }
                        setLoading(false);
                    }}
                >生成SQL</Button>
                <Button
                    style={{
                        width: '220px'
                    }}
                    loading={loading}
                    disabled={props.dataSource.storage_type !== databaseType}
                    type={'primary'}
                    onClick={async () => {
                        setLoading(true);
                        try {
                            await execute({
                                database_type: 'sqlite',
                                protocol: 'sqlite',
                                options: {},
                                ...JSON.parse(props.dataSource.storage_options),
                                id: props.dataSource.id
                            }, content, [], {
                                options: {}
                            });
                        } catch (err) {
                            console.error(err);
                        }
                        setLoading(false);
                    }}
                >执行</Button>
            </Top>
            <SQLEditorContainer ref={monacoEl}>
            </SQLEditorContainer>
        </Container>
    );
}


const Container = styled.div`
    width: 100%;
    height: 100%;
    padding: 6px 6px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    gap: 10px;
`;


const Top = styled.div`
    width: 100%;
    height: 90px;
    background-color: #FFFFFF;
    display: flex;
    align-items: center;
    justify-content: center;
`;


const SQLEditorContainer = styled.div`
    width: 100%;
    min-width: 300px;
    flex: 1;
    border-bottom: 1px solid #d9d9d9;
    background-color: #FFFFFF;
`;
